//
//  JMAnswerViewController.m
//  VoluntaryStar
//
//  Created by xiaorui on 15/9/7.
//  Copyright (c) 2015年 ios. All rights reserved.
//

#import "JMAnswerViewController.h"
#import "JMAnswerCell.h"
#import "JMStudyCircleCell.h"
#import "JMAnswerViewMode.h"
#import <UIImageView+WebCache.h>
#import "JMAnswerMode.h"
#import <UIImageView+WebCache.h>
#import "JMMyAnswerViewController.h"

@interface JMAnswerViewController ()<UITableViewDelegate,UITableViewDataSource>{

    int  lastId;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIButton *answerBtn;

@property (nonatomic, strong) UIView *bottomView;

@end

@implementation JMAnswerViewController

- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WITH, UI_SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.backgroundView.backgroundColor = [UIColor clearColor];
        _tableView = tableView;
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _dataArray;
}

- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]init];
        _bottomView.backgroundColor = [UIColor whiteColor];
        _bottomView.frame = CGRectMake(0, UI_SCREEN_HEIGHT - 60, UI_SCREEN_WITH, 60);
        
    }
    return _bottomView;
}

- (UIButton *)answerBtn
{
    if (!_answerBtn) {
        UIButton *button = [[UIButton alloc]init];
        [button setTitle:@"回答" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(answerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        button.backgroundColor = UIColorFromRGB(0xeb6100);
        button.frame = CGRectMake(10, 10, UI_SCREEN_WITH - 20, self.bottomView.frameHeight - 20);
        _answerBtn = button;
    }
    return _answerBtn;
}

-(void)answerButtonClick:(UIButton *)sender{
    JMMyAnswerViewController *vc =[JMMyAnswerViewController new];
    vc.mode =self.mode;
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationItem.title =@"回答";
    self.backBtn.hidden = YES;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.answerBtn];
    
    lastId = 0;
    [self setupRefresh];
}
#pragma mark 上下拉刷新数据
- (void)setupRefresh{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    [self.tableView.header beginRefreshing];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
}
-(void)headerRereshing{
    lastId = 0;
    [self getDataFromeServer];
}
-(void)footerRereshing{
    [self getDataFromeServer];
}

-(void)getDataFromeServer{
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:cf.user.userId forKey:@"user"];
        [dict setObject:cf.user.token forKey:@"token"];
        [dict setObject:@"list" forKey:@"act"];
        [dict setObject:[NSString stringWithFormat:@"%d",lastId] forKey:@"last"];
        [dict setObject:@"15" forKey:@"size"];
        [dict setObject:[NSString stringWithFormat:@"%d",self.mode.questionId ] forKey:@"qid"];
        
        [JMAnswerViewMode fetchAnswerQuestionParametes:dict block:^(id data, NSError *error, id currData) {
            [JMTools hiddenAlerView:self.view];

            if([data[@"status"] integerValue] == 1){
                if(lastId == 0)[self.dataArray removeAllObjects];
                if(lastId == [[[currData lastObject] anserId] intValue] || [currData count] == 0){
                    [JMTools showAlertView:self.view message:@"没有更多数据"];
                }else{
                    [self.dataArray addObjectsFromArray:currData];
                    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
                    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
                }
            }else{
                
            }
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
        }];
    }


}
#pragma mark  tableView delegate dasouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 1;
    }
    return  self.dataArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        static NSString *str = @"IDD";
        JMStudyCircleCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
        if(!cell){
            cell = [[JMStudyCircleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
            cell.countBnt.hidden =YES;
            cell.answerBnt.selected = NO;
            cell.selected =NO;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell.answerBnt setTitle:@"提问者" forState:UIControlStateNormal];
        [cell.iconImageView  sd_setImageWithURL:[NSURL URLWithString:self.mode.picString]];
        cell.nameLabel.text = self.mode.loginString;
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
        [formatter setDateFormat : @"yyyy-MM-dd HH:mm:ss"];
        [formatter setTimeZone:timeZone];
        NSDate *dateTime = [formatter dateFromString:self.mode.timeString];
        NSDate *dateNow = [NSDate date];
        cell.timelabel.text = [NSString dateInterval:dateTime nowDate:dateNow];
        cell.typeLabel.text = [NSString stringWithFormat:@"%@%@",self.mode.gradeString,self.mode.subjectString];
        cell.typeLabel.textColor = self.mode.typeColor;
        cell.typeLabel.layer.borderColor = [self.mode.typeColor CGColor];
        
        [cell.infoImageView sd_setImageWithURL:[NSURL URLWithString:self.mode.logoString]];        return cell;
        return cell;
    }else{
        static NSString *str = @"IDE";
        JMAnswerCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
        if(!cell){
            cell = [[JMAnswerCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
        }
        JMAnswerMode *mode = self.dataArray[indexPath.row];
        [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:mode.picString]];
        cell.nameLabel.text = mode.loginString;
        cell.timeLabel.text = mode.ask_timeString;
        cell.textView.text = mode.ask_detailString;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return   UI_SCREEN_WITH *0.546875;
    }else{
        return UI_SCREEN_WITH *0.3;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
